package terra.model.map;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPOutputStream;

import terra.managers.MapManager;
import terra.model.object.GameObject;
import terra.model.object.NpcObject;
import terra.model.object.StaticObject;

public class MapSaver implements Runnable {

	Map toSave;
	boolean del = false;

	public MapSaver(Map toSave, boolean delete) {
		this.toSave = toSave;
		del = delete;
	}

	@Override
	public void run() {
		try {
			File map = new File("map" + File.separator + toSave.index + ".map");
			if (!map.exists())
				map.createNewFile();

			FileOutputStream fos = new FileOutputStream(map);
			GZIPOutputStream gz = new GZIPOutputStream(fos);
			ObjectOutputStream oos = new ObjectOutputStream(gz);
			oos.writeObject(toSave.container);
			oos.flush();
			oos.close();
			gz.flush();
			gz.close();
			fos.flush();
			fos.close();
			if (del) {
				MapManager.instance.getMaps().remove(toSave.index);
				MapManager.instance.getWaitingMaps().remove(
						(Integer) toSave.index);
				MapManager.instance.mapRemoved(toSave.index);
				System.out.println("Saved and deleted " + toSave.index);
				// Runtime.getRuntime().gc();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		for(GameObject obj: toSave.getObjects().values()){
			if (obj instanceof NpcObject){
				((NpcObject) obj).saveNpc();
			} else if (obj instanceof StaticObject)
				((StaticObject) obj).saveStaticObject();
		}
		
		
	}

}
